package net.esj.basic.core.engine.tools.crypt;

import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import javax.crypto.Cipher;

import net.esj.basic.utils.StringUtils;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

public class RSACryptImpl implements AsymCrypt {
	
	static Logger logger =Logger.getLogger(RSACryptImpl.class);
	
	private String DEFAULT_SECRET_KEY = "UYHGT^&%6TF*4VPL.U^9FA!SWR3sOPe4@B*jhgFO(JNT*_)JKHaJi&Ka!lo~KOUW";

	private int encryptType = ASYMMETRIC_KEY_ENCRYPR_TYPE_PUBLIC;
	
	
	final int KEY_SIZE = 1024;
	
	@Override
	public KeyPair generateKeyPair(byte[] keyInfo) {
		KeyPairGenerator keygen;
		try {
			keygen = KeyPairGenerator.getInstance("RSA");
			SecureRandom random = new SecureRandom();
			random.setSeed(keyInfo); // 初始加密，长度为512，必须是大于512才可以的
			keygen.initialize(KEY_SIZE,random);
			// 取得密钥对
			KeyPair kp = keygen.generateKeyPair(); 
			return kp;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public PrivateKey getPrivateKey(byte[] keyInfo) {
		KeyPair kp = generateKeyPair(keyInfo);
		return kp.getPrivate();
	}

	@Override
	public PublicKey getPublicKey(byte[] keyInfo) {
		KeyPair kp = generateKeyPair(keyInfo);
		return kp.getPublic();
	}

	@Override
	public byte[] decrypt(byte[] bytes) {
		return decrypt(bytes,DEFAULT_SECRET_KEY.getBytes());
	}

	@Override
	public byte[] decrypt(byte[] bytes, byte[] decryptPass) {
		Cipher cipher;
		try {
			cipher = Cipher.getInstance("RSA");
			PrivateKey key = getPrivateKey(decryptPass);
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] debytes = cipher.doFinal(bytes);
			return debytes;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}

	@Override
	public String decrypt(String content) {
		return decrypt(content,DEFAULT_SECRET_KEY.getBytes());
	}

	@Override
	public String decrypt(String content, byte[] decryptPass) {
		byte[] bytes = StringUtils.parseHexStr2Byte(content);
		byte[] debytes =  decrypt(bytes, decryptPass);
		return new String(debytes);
	}

	@Override
	public byte[] encrypt(byte[] bytes) {
		return encrypt(bytes,DEFAULT_SECRET_KEY.getBytes());
	}

	@Override
	public byte[] encrypt(byte[] bytes, byte[] encryptPass) {
		Cipher cipher;
		try {
			cipher = Cipher.getInstance("RSA");
			Key key = getPublicKey(encryptPass);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return cipher.doFinal(bytes);
		} catch (Exception e) {
			logger.error("ERROR encrypt IN RSACrypt", e);
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String encrypt(String content) {
		return encrypt(content,DEFAULT_SECRET_KEY.getBytes());
	}

	@Override
	public String encrypt(String content, byte[] encryptPass) {
		try {
			byte[] bytes = content.getBytes("UTF-8");
			byte[] en = encrypt(bytes,encryptPass);
			return StringUtils.parseByte2HexStr(en);
		} catch (UnsupportedEncodingException e) {
			logger.error("ERROR encrypt IN RSACrypt", e);
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void setDefaultSecretKey(String key) {
		this.DEFAULT_SECRET_KEY = key;
	}

	public static void main(String[] args){
		Crypt crypt = new RSACryptImpl();
		String test = "你是一头猪";
		String en = crypt.encrypt(test);
		System.out.println(en);
		String de = crypt.decrypt(en);
		System.out.println(de);
	}

	@Override
	public void setEncryptType(int type) {
		if(type!=ASYMMETRIC_KEY_ENCRYPR_TYPE_PRIVATE&& type!=ASYMMETRIC_KEY_ENCRYPR_TYPE_PUBLIC){
			return;
		}
		encryptType = type;
	}

	@Override
	public boolean checksum(byte[] bytes, byte[] encryptPass, byte[] results) {
		Assert.notNull(results);
		byte[] encrypts = encrypt(bytes, encryptPass);
		if(encrypts.length!=results.length){
			return false;
		}
		for(int i =0 ;i<encrypts.length;i++){
			if(encrypts[i] != results[i]){
				return false;
			}
		}
		return true;
	}
	
	@Override
	public boolean checksum(byte[] bytes, byte[] results) {
		return checksum(bytes, DEFAULT_SECRET_KEY.getBytes(), results);
	}

	@Override
	public boolean checksum(String content, byte[] encryptPass, String results) {
		Assert.notNull(results);
		String encrypt = encrypt(content, encryptPass);
		if(encrypt.equals(results)){
			return true;
		}
		return false;
	}


	@Override
	public boolean checksum(String content, String results) {
		return checksum(content, DEFAULT_SECRET_KEY.getBytes(), results);
	}
}
